package com.ztesoft.book.common.utils.encrypt;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSON;
import com.ztesoft.book.common.constant.Constant;
import com.ztesoft.book.common.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * author: mc
 * date: 2021-07-29
 */
@Slf4j
public abstract class RSAUtil {

    /**
     * 登录参数解密
     *
     * @param json      json字符串
     * @param publicKey 公钥
     * @return
     */
    public static <T> T getDecodeObj(String json, String publicKey, Class<T> clazz) {
        try {
            List<String> list = JSON.parseArray(json, String.class);
            String privateKey = RedisUtils.get(Constant.PUBLIC_KEY_PREFIX + publicKey);
            StringBuilder sb = new StringBuilder();
            if (StringUtils.hasLength(privateKey)) {
                RSA rsa = new RSA(privateKey, null);
                list.forEach(e -> {
                    byte[] aByte = Base64Utils.decode(e.getBytes());
                    byte[] decrypt = rsa.decrypt(aByte, KeyType.PrivateKey);
                    sb.append(new String(decrypt, StandardCharsets.UTF_8));
                });
                return JSON.parseObject(sb.toString(), clazz);
            }
            return null;
        }
        catch (Exception e) {
            log.error("参数解密错误：", e);
            return null;
        }
    }
}
